<template>
  <div class="user-profile">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>个人中心</h2>
      <p>管理您的个人信息</p>
    </div>

    <!-- 信息卡片 -->
    <el-card class="profile-card">
      <!-- 头像区域 -->
      <div class="avatar-section">
        <el-avatar :size="140" class="user-avatar">
          <img :src="userInfo.avatar" alt="用户头像" class="avatar-img" />
        </el-avatar>
        <div class="avatar-actions">
          <el-button
            type="primary"
            size="small"
            @click="handleAvatarUpload"
            icon="Upload"
            class="upload-btn"
          >
            更换头像
          </el-button>
          <p class="avatar-tip" v-if="isEditing">
            支持JPG、PNG格式，大小不超过1GB
          </p>
        </div>
        <!-- 隐藏的文件输入框 -->
        <input
          type="file"
          ref="avatarInput"
          accept="image/*"
          class="avatar-input"
          @change="onAvatarChange"
          style="display: none"
        />
      </div>

      <!-- 信息表单 -->
      <el-form
        ref="userForm"
        :model="formData"
        :rules="formRules"
        label-width="130px"
        class="info-form"
      >
        <div class="form-grid">
          <!-- 左侧表单区域 -->
          <div class="form-column">
            <!-- 昵称 -->
            <el-form-item label="昵称" prop="userName" class="form-item">
              <el-input
                v-model="formData.userName"
                :disabled="!isEditing"
                placeholder="请输入昵称"
                class="form-input"
              ></el-input>
            </el-form-item>

            <!-- 手机号 -->
            <el-form-item
              label="手机号"
              prop="phone"
              :rules="isEditing ? formRules.phone : []"
              class="form-item"
            >
              <el-input
                v-model="formData.phone"
                :disabled="!isEditing"
                placeholder="请输入手机号"
                class="form-input"
              ></el-input>
              <template v-if="isEditing" #help>
                <el-input
                  v-model="formData.oldPhone"
                  placeholder="请输入原手机号进行验证"
                  class="old-phone-input"
                ></el-input>
              </template>
            </el-form-item>
          </div>

          <!-- 右侧表单区域 -->
          <div class="form-column">
            <!-- 身份证号 -->
            <el-form-item label="身份证号" prop="idCard" class="form-item">
              <el-input
                :value="displayIdCard"
                readonly
                placeholder="未填写"
                class="form-input"
              ></el-input>
              <template #help>
                <span v-if="!isEditing" class="help-text">
                  {{
                    idCardEditable
                      ? "点击编辑可填写身份证号"
                      : "身份证号一旦填写不可修改"
                  }}
                </span>
                <span v-if="isEditing && idCardEditable" class="help-text">
                  请输入真实身份证号，提交后不可修改
                </span>
              </template>
              <el-input
                v-if="isEditing && idCardEditable"
                v-model="formData.idCard"
                type="password"
                placeholder="请输入身份证号"
                class="idcard-input"
              ></el-input>
            </el-form-item>

            <!-- 注册时间 -->
            <el-form-item label="注册时间" class="form-item">
              <el-input
                v-model="formData.registerTime"
                readonly
                placeholder="--"
                class="form-input"
              ></el-input>
            </el-form-item>

            <!-- 用户类型 -->
            <el-form-item label="用户类型" class="form-item">
              <el-input
                v-model="userTypeText"
                readonly
                placeholder="--"
                class="form-input"
              ></el-input>
            </el-form-item>
          </div>
        </div>

        <!-- 操作按钮 -->
        <el-form-item class="form-actions">
          <el-button
            v-if="!isEditing"
            type="primary"
            @click="isEditing = true"
            class="edit-btn"
          >
            编辑信息
          </el-button>
          <template v-else>
            <el-button type="success" @click="handleSave" class="save-btn">
              保存修改
            </el-button>
            <el-button type="info" @click="handleCancel" class="cancel-btn">
              取消
            </el-button>
          </template>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, reactive } from "vue";
import { ElMessage, ElLoading } from "element-plus";
import { Upload } from '@element-plus/icons-vue'
import authHttp from "@/util/request";
import axios from "axios";
import { useCounterStore } from '@/stores/counter'
import router from '@/router'

// Pinia状态
const userStore = useCounterStore()

// 手机号验证函数
const validatePhoneChange = (rule, value, callback) => {
  if (
    formData.value.oldPhone &&
    formData.value.oldPhone !== originalData.phone
  ) {
    callback(new Error("原手机号验证错误"));
  } else {
    callback();
  }
};

// 状态管理
const userInfo = ref({});
const formData = ref({
  userName: "",
  phone: "",
  idCard: "",
  registerTime: "",
  oldPhone: "",
});
const isEditing = ref(false);
const avatarInput = ref(null);
const userForm = ref(null);
let originalData = {};
let tempAvatarUrl = "";

// 表单规则
const formRules = reactive({
  userName: [
    { required: true, message: "请输入昵称", trigger: "blur" },
    { min: 2, max: 10, message: "昵称长度在 2-10 个字符", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入新手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号格式",
      trigger: "blur",
    },
    { validator: validatePhoneChange, trigger: "blur" },
  ],
  idCard: [
    { required: true, message: "请输入身份证号", trigger: "blur" },
    {
      pattern: /(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: "请输入正确的身份证号",
      trigger: "blur",
    },
  ],
});

// 身份证号显示处理
const displayIdCard = computed(() => {
  if (!formData.value.idCard) return "";
  const idCard = String(formData.value.idCard).trim();
  if (idCard.length === 18) {
    return idCard.slice(0, 6) + "********" + idCard.slice(-4);
  }
  if (idCard.length > 10) {
    return idCard.slice(0, 6) + "***" + idCard.slice(-4);
  }
  return idCard;
});

// 身份证号是否可编辑
const idCardEditable = computed(() => {
  return !formData.value.idCard || formData.value.idCard.trim() === "";
});

// 用户类型文本转换
const userTypeText = computed(() => {
  const typeMap = {
    0: "用户",
    1: "商户",
    2: "商户与用户",
  };
  return typeMap[userInfo.value.userType] || "未知类型";
});

// 获取用户信息并同步到Pinia
const getUserInfo = async () => {
  try {
    const { data: response } = await authHttp.post(
      "/eduservice/user/Myzhongxin"
    );
    if (response.user) {
      userInfo.value = response.user;
      // 更新表单数据
      formData.value = {
        ...formData.value,
        userName: response.user.userName || "",
        phone: response.user.phone || "",
        idCard: response.user.idCard || "",
        registerTime: response.user.registerTime || "",
        avatar: response.user.avatar || "",
      };
      originalData = { ...formData.value };
      // tempAvatarUrl = userInfo.value.avatar || "";
      // 同步到Pinia（关键：让App页面实时获取）
      userStore.updateUserInfo(response.user);
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
    ElMessage.error("获取个人信息失败，请稍后重试");
  }
};

// 头像上传相关
const handleAvatarUpload = () => {
  if (isEditing.value) {
    avatarInput.value.click();
  } else {
    ElMessage.info("请先点击编辑信息");
  }
};

const onAvatarChange = async (e) => {
  const file = e.target.files[0];
  if (!file) return;

  // 验证文件类型
  if (!file.type.match(/^image\/(jpeg|png|jpg)$/)) {
    ElMessage.error("请上传JPG或PNG格式的图片");
    return;
  }

  // 验证文件大小（修正：1GB太大，调整为5MB更合理）
  if (file.size > 1024 * 1024 * 5) {
    ElMessage.error("图片大小不能超过5MB");
    return;
  }

  const loading = ElLoading.service({ text: "上传中，请稍候..." });

  try {
    const formData = new FormData();
    formData.append("file", file);
    const { data } = await axios.post(
      "/serviceoss/fileoss/uploadAvatarToOss",
      formData,
      {
        headers: { "Content-Type": "multipart/form-data" },
      }
    );

    if (data.code === 20000 && data.data.url) {
      tempAvatarUrl = data.data.url;
      userInfo.value.avatar = tempAvatarUrl;
      console.log('tempAvatarUrl',tempAvatarUrl)
      ElMessage.success("头像上传成功");
    } else {
      ElMessage.error("头像上传失败：" + (data.message || "未知错误"));
    }
  } catch (error) {
    console.error("头像上传失败:", error);
    ElMessage.error("头像上传失败，请重试");
  } finally {
    loading.close();
    e.target.value = "";
  }
};

// 保存修改
const handleSave = async () => {
  const loading = ElLoading.service({ text: "保存中，请稍候..." });
  try {
    await userForm.value.validate();

    const submitData = {
      userName: formData.value.userName,
      phone: formData.value.phone,
      avatar: tempAvatarUrl,
      ...(idCardEditable.value &&
        formData.value.idCard && { idCard: formData.value.idCard }),
    };

    const response = await authHttp.post(
      "/eduservice/user/updateInfo",
      submitData
    );

    if (response.message === "更新成功") {
      ElMessage.success("信息更新成功");
      // 合并更新后的数据（包含所有用户信息）
      const updatedUserInfo = {
        ...userInfo.value,
        ...submitData,
        userId: userStore.userId // 保留原始用户ID
      };
      // 同步到Pinia（App页面会实时更新）
      userStore.updateUserInfo(updatedUserInfo);
      // 刷新页面确保所有组件同步
    window.location.reload();
    } else {
      ElMessage.success(response.message);
    }

    isEditing.value = false;
    originalData = { ...formData.value };
    formData.value.oldPhone = "";
  } catch (error) {
    console.error("保存信息失败:", error);
    if (error.name !== "Error") return;
    ElMessage.error("保存信息失败，请重试");
  } finally {
    loading.close();
  }
};

// 取消编辑
const handleCancel = () => {
  userInfo.value.avatar = originalData.avatar || "";
  tempAvatarUrl = originalData.avatar || "";
  formData.value = { ...originalData };
  formData.value.oldPhone = "";
  isEditing.value = false;
  userForm.value?.clearValidate();
};

// 初始化
onMounted(() => {
  getUserInfo();
});
</script>

<style scoped>
.user-profile {
  padding: 30px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #f9fafb;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.page-header h2 {
  font-size: 26px;
  color: #1d2129;
  margin: 0 0 10px 0;
  font-weight: 600;
}

.page-header p {
  color: #86909c;
  font-size: 14px;
  margin: 0;
}

.profile-card {
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.05);
  border: none;
  overflow: hidden;
  background-color: #fff;
}

.avatar-section {
  display: flex;
  align-items: center;
  padding: 30px;
  border-bottom: 1px solid #f2f3f5;
  margin-bottom: 30px;
  gap: 25px;
}

.user-avatar {
  width: 140px;
  height: 140px;
  border: 4px solid #f7f8fa;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s ease;
}

.user-avatar:hover {
  transform: scale(1.05);
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

.avatar-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.upload-btn {
  padding: 8px 20px;
  transition: all 0.2s ease;
}

.upload-btn:hover {
  transform: translateY(-2px);
}

.avatar-tip {
  font-size: 12px;
  color: #86909c;
  margin: 0;
}

.info-form {
  padding: 0 40px 30px;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30px;
}

.form-column {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-item {
  margin-bottom: 0 !important;
  padding: 15px 0;
  border-bottom: 1px dashed #f2f3f5;
}

.form-item:last-child {
  border-bottom: none;
}

.el-form-item__label {
  font-size: 14px;
  color: #4e5969;
  font-weight: 500;
  padding-right: 20px !important;
  line-height: 40px;
}

.el-form-item__content {
  line-height: 40px;
}

.form-input {
  width: 100%;
  height: 42px;
  border-radius: 6px;
  border-color: #dcdfe6;
  padding: 0 15px;
  transition: all 0.2s;
  font-size: 14px;
}

.form-input:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.help-text {
  font-size: 12px;
  color: #86909c;
  line-height: 1.5;
  margin-top: 5px;
}

.old-phone-input {
  margin-top: 10px;
  width: 100%;
  height: 38px;
  font-size: 13px;
}

.idcard-input {
  margin-top: 10px;
  width: 100%;
  height: 38px;
}

.form-actions {
  margin-top: 35px !important;
  padding: 20px 0 10px;
  border-top: 1px solid #f2f3f5;
  display: flex;
  justify-content: center;
  gap: 15px;
}

.edit-btn,
.save-btn,
.cancel-btn {
  min-width: 120px;
  height: 42px;
  font-size: 14px;
  padding: 0 20px;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.save-btn {
  background-color: #52c41a;
  border-color: #52c41a;
}

.save-btn:hover {
  background-color: #4cae1a;
  border-color: #4cae1a;
  transform: translateY(-2px);
}

.cancel-btn {
  background-color: #f5f7fa;
  color: #4e5969;
  border-color: #dcdfe6;
}

.cancel-btn:hover {
  background-color: #e9ecef;
  transform: translateY(-2px);
}

@media (max-width: 768px) {
  .user-profile {
    padding: 15px;
  }

  .form-grid {
    grid-template-columns: 1fr;
  }

  .avatar-section {
    flex-direction: column;
    align-items: center;
    text-align: center;
    padding: 20px 15px;
  }

  .avatar-actions {
    align-items: center;
    margin-left: 0;
    margin-top: 15px;
  }

  .form-actions {
    flex-direction: column;
    gap: 10px;
  }

  .edit-btn,
  .save-btn,
  .cancel-btn {
    width: 100%;
  }
}
</style>